<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model="searchForm"
      :items="formItems"
      :show-expand="true"
      @search="handleSearch"
      @reset="resetSearchParams"
    />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap>
            <ElButton type="primary" @click="handleRefresh"> 刷新数据 </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        :show-overflow-tooltip="true"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 状态-->
        <template #dataStatus="{ row }">
          {{ row.dataStatus === 0 ? '可用' : '不可用' }}
        </template>

        <!-- 报事时间-->
        <template #recordTime="{ row }">
          {{ formatDateTime(row.recordTime) }}
        </template>

        <!-- 报事类型列 -->
        <template #recordType="{ row }">
          <DictTag
            :dict-type="'10200'"
            :value="row.recordType"
            :fallback-text="getRecordTypeText(row.recordType)"
            :auto-tag-type="true"
          />
        </template>

        <!-- 紧急程度列 -->
        <template #recordUrgentType="{ row }">
          <DictTag
            :dict-type="'10310'"
            :value="row.recordUrgentType"
            :fallback-text="getUrgentTypeText(row.recordUrgentType)"
            :auto-tag-type="true"
          />
        </template>

        <!-- 处理状态列 -->
        <template #recordStatus="{ row }">
          <DictTag
            :dict-type="'10300'"
            :value="row.recordStatus"
            :fallback-text="getRecordStatusText(row.recordStatus)"
            :auto-tag-type="true"
          />
        </template>

        <!-- 解决状态列 -->
        <template #recordSolveStatus="{ row }">
          <DictTag
            :dict-type="'10210'"
            :value="row.recordSolveStatus"
            :fallback-text="getSolveStatusText(row.recordSolveStatus)"
            :auto-tag-type="true"
          />
        </template>

        <!-- 附件列 -->
        <template #recordFile="{ row }">
          <div v-if="getAttachmentList(row.recordFile).length > 0" class="attachment-container">
            <div
              v-for="(attachment, index) in getAttachmentList(row.recordFile)"
              :key="index"
              class="attachment-item"
            >
              <div v-if="isImageFile(attachment.url)" class="image-preview">
                <ElImage
                  :src="attachment.url"
                  :preview-src-list="getImageUrls(row.recordFile)"
                  :initial-index="getImageIndex(row.recordFile, attachment.url)"
                  fit="cover"
                  class="attachment-image"
                  :preview-teleported="true"
                />
              </div>
              <div v-else class="file-link">
                <ElLink :href="attachment.url" target="_blank" type="primary">
                  <ElIcon><Document /></ElIcon>
                  查看附件
                </ElLink>
              </div>
            </div>
          </div>
          <span v-else class="text-gray-400">无附件</span>
        </template>
        <!--  回复附件 -->
        <template #recordReplyFile="{ row }">
          <div
            v-if="row.recordReplyFile != null && getAttachmentList(row.recordReplyFile).length > 0"
            class="attachment-container"
          >
            <div
              v-for="(attachment, index) in getAttachmentList(row.recordReplyFile)"
              :key="index"
              class="attachment-item"
            >
              <div v-if="isImageFile(attachment.url)" class="image-preview">
                <ElImage
                  :src="attachment.url"
                  :preview-src-list="getImageUrls(row.recordReplyFile)"
                  :initial-index="getImageIndex(row.recordReplyFile, attachment.url)"
                  fit="cover"
                  class="attachment-image"
                  :preview-teleported="true"
                />
              </div>
              <div v-else class="file-link">
                <ElLink :href="attachment.url" target="_blank" type="primary">
                  <ElIcon><Document /></ElIcon>
                  查看附件
                </ElLink>
              </div>
            </div>
          </div>
          <span v-else class="text-gray-400">无附件</span>
        </template>

        <!--评价 -->
        <template #recordScoreStatus="{ row }">
          <DictTag
            :dict-type="'10200'"
            :value="row.recordScoreStatus"
            :fallback-text="getUrgentTypeText(row.recordScoreStatus)"
            :auto-tag-type="true"
          />
        </template>

        <!-- 创建时间格式化 -->
        <template #createTime="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>

        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex items-center gap-2">
            <ArtButtonTable type="view" @click="handleView(row)"> 查看 </ArtButtonTable>
            <ArtButtonTable type="edit" @click="handleProcess(row)" v-if="row.recordStatus == 1">
              处理
            </ArtButtonTable>
            <ArtButtonTable type="edit" @click="handleSolve(row)" v-if="row.recordStatus === 2">
              解决
            </ArtButtonTable>
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 处理报事弹框 -->
    <ElDialog
      v-model="processDialogVisible"
      title="处理报事"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <ElForm
        ref="processFormRef"
        :model="processForm"
        :rules="processFormRules"
        label-width="100px"
      >
        <!-- <ElFormItem label="报事ID">
          <ElInput v-model="processForm.id" disabled />
        </ElFormItem> -->

        <ElFormItem label="处理状态" prop="recordStatus">
          <DictSelect
            v-model="processForm.recordStatus"
            dict-type="10300"
            placeholder="请选择处理状态"
            clearable
          />
        </ElFormItem>

        <ElFormItem label="回复内容" prop="recordReplyInfo">
          <ElInput
            v-model="processForm.recordReplyInfo"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
            maxlength="500"
            show-word-limit
          />
        </ElFormItem>

        <ElFormItem label="回复附件">
          <ProUploadFile
            v-model:fileList="replyFileList"
            action="/api/api/ossFile/saveFile"
            :limit="5"
            accept="image/*,.pdf,.doc,.docx,.xls,.xlsx"
            :file-size="10"
            @success="handleFileUploadSuccess"
          />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <ElSpace>
          <ElButton @click="processDialogVisible = false">取消</ElButton>
          <ElButton type="primary" @click="handleProcessSubmit" :loading="processLoading">
            确定处理
          </ElButton>
        </ElSpace>
      </template>
    </ElDialog>

    <!-- 解决报事弹框 -->
    <ElDialog
      v-model="solveDialogVisible"
      title="解决报事"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <ElForm ref="solveFormRef" :model="solveForm" :rules="solveFormRules" label-width="100px">
        <ElFormItem label="回复内容" prop="recordReplyInfo">
          <ElInput
            v-model="solveForm.recordReplyInfo"
            type="textarea"
            :rows="4"
            placeholder="请输入解决回复内容"
            maxlength="500"
            show-word-limit
          />
        </ElFormItem>

        <ElFormItem label="回复附件">
          <ProUploadFile
            v-model:fileList="solveReplyFileList"
            action="/api/api/ossFile/saveFile"
            :limit="5"
            accept="image/*,.pdf,.doc,.docx,.xls,.xlsx"
            :file-size="10"
            @success="handleSolveFileUploadSuccess"
          />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <ElSpace>
          <ElButton @click="solveDialogVisible = false">取消</ElButton>
          <ElButton type="primary" @click="handleSolveSubmit" :loading="solveLoading">
            确定解决
          </ElButton>
        </ElSpace>
      </template>
    </ElDialog>

    <!-- 查看详情弹框 -->
    <ElDialog
      v-model="viewDialogVisible"
      title="报事详情"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-if="viewDetailData" class="detail-container">
        <ElRow :gutter="20">
          <ElCol :span="12">
            <div class="detail-item">
              <label>用户名称：</label>
              <span>{{ viewDetailData.newUser?.newName || '暂无' }}</span>
            </div>
          </ElCol>
          <ElCol :span="12">
            <div class="detail-item">
              <label>小区名称：</label>
              <span>{{ viewDetailData.geoArea?.areaName || '暂无' }}</span>
            </div>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <div class="detail-item">
              <label>报事类型：</label>
              <DictTag
                :dict-type="'10200'"
                :value="viewDetailData.recordType"
                :fallback-text="getRecordTypeText(viewDetailData.recordType)"
                :auto-tag-type="true"
              />
            </div>
          </ElCol>
          <ElCol :span="12">
            <div class="detail-item">
              <label>紧急程度：</label>
              <DictTag
                :dict-type="'10310'"
                :value="viewDetailData.recordUrgentType"
                :fallback-text="getUrgentTypeText(viewDetailData.recordUrgentType)"
                :auto-tag-type="true"
              />
            </div>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <div class="detail-item">
              <label>处理状态：</label>
              <DictTag
                :dict-type="'10300'"
                :value="viewDetailData.recordStatus"
                :fallback-text="getRecordStatusText(viewDetailData.recordStatus)"
                :auto-tag-type="true"
              />
            </div>
          </ElCol>
          <ElCol :span="12">
            <div class="detail-item">
              <label>解决状态：</label>
              <DictTag
                :dict-type="'10210'"
                :value="viewDetailData.recordSolveStatus"
                :fallback-text="getSolveStatusText(viewDetailData.recordSolveStatus)"
                :auto-tag-type="true"
              />
            </div>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <div class="detail-item">
              <label>经度：</label>
              <span>{{ viewDetailData.recordLongitude || '暂无' }}</span>
            </div>
          </ElCol>
          <ElCol :span="12">
            <div class="detail-item">
              <label>纬度：</label>
              <span>{{ viewDetailData.recordLatitude || '暂无' }}</span>
            </div>
          </ElCol>
        </ElRow>

        <div class="detail-item">
          <label>位置信息：</label>
          <span>{{ viewDetailData.recordAddress || '暂无' }}</span>
        </div>

        <div class="detail-item">
          <label>报事时间：</label>
          <span>{{ formatDateTime(viewDetailData.recordTime) }}</span>
        </div>

        <div class="detail-item">
          <label>问题描述：</label>
          <div class="detail-content">{{ viewDetailData.recordDescribe || '暂无' }}</div>
        </div>

        <div class="detail-item">
          <label>附件：</label>
          <div
            v-if="
              viewDetailData.recordFile && getAttachmentList(viewDetailData.recordFile).length > 0
            "
            class="attachment-container"
          >
            <div
              v-for="(attachment, index) in getAttachmentList(viewDetailData.recordFile)"
              :key="index"
              class="attachment-item"
            >
              <div v-if="isImageFile(attachment.url)" class="image-preview">
                <ElImage
                  :src="attachment.url"
                  :preview-src-list="getImageUrls(viewDetailData.recordFile || '')"
                  :initial-index="getImageIndex(viewDetailData.recordFile || '', attachment.url)"
                  fit="cover"
                  class="attachment-image"
                  :preview-teleported="true"
                />
              </div>
              <div v-else class="file-link">
                <ElLink :href="attachment.url" target="_blank" type="primary">
                  <ElIcon><Document /></ElIcon>
                  查看附件
                </ElLink>
              </div>
            </div>
          </div>
          <span v-else class="text-gray-400">无附件</span>
        </div>

        <div v-if="viewDetailData.recordReplyInfo" class="detail-item">
          <label>回复内容：</label>
          <div class="detail-content">{{ viewDetailData.recordReplyInfo }}</div>
        </div>

        <div v-if="viewDetailData.recordReplyFile" class="detail-item">
          <label>回复附件：</label>
          <div
            v-if="getAttachmentList(viewDetailData.recordReplyFile).length > 0"
            class="attachment-container"
          >
            <div
              v-for="(attachment, index) in getAttachmentList(viewDetailData.recordReplyFile)"
              :key="index"
              class="attachment-item"
            >
              <div v-if="isImageFile(attachment.url)" class="image-preview">
                <ElImage
                  :src="attachment.url"
                  :preview-src-list="getImageUrls(viewDetailData.recordReplyFile || '')"
                  :initial-index="
                    getImageIndex(viewDetailData.recordReplyFile || '', attachment.url)
                  "
                  fit="cover"
                  class="attachment-image"
                  :preview-teleported="true"
                />
              </div>
              <div v-else class="file-link">
                <ElLink :href="attachment.url" target="_blank" type="primary">
                  <ElIcon><Document /></ElIcon>
                  查看附件
                </ElLink>
              </div>
            </div>
          </div>
          <span v-else class="text-gray-400">无附件</span>
        </div>

        <div v-if="viewDetailData.recordScoreStatus" class="detail-item">
          <label>评价：</label>
          <DictTag
            :dict-type="'10200'"
            :value="viewDetailData.recordScoreStatus"
            :fallback-text="getUrgentTypeText(viewDetailData.recordScoreStatus)"
            :auto-tag-type="true"
          />
        </div>

        <div v-if="viewDetailData.recordScoreInfo" class="detail-item">
          <label>评价内容：</label>
          <div class="detail-content">{{ viewDetailData.recordScoreInfo }}</div>
        </div>

        <div class="detail-item">
          <label>创建时间：</label>
          <span>{{ formatDateTime(viewDetailData.createTime) }}</span>
        </div>
      </div>

      <div v-else class="loading-container">
        <ElSkeleton :rows="8" animated />
      </div>

      <template #footer>
        <ElSpace>
          <ElButton @click="viewDialogVisible = false">关闭</ElButton>
        </ElSpace>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, h } from 'vue'
  import {
    dayjs,
    ElMessage,
    ElImage,
    ElLink,
    ElIcon,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElSpace,
    ElRow,
    ElCol,
    ElSkeleton
  } from 'element-plus'
  import { Document } from '@element-plus/icons-vue'
  import { useTable } from '@/composables/useTable'
  import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { DictTag, DictSelect } from '@/components/core/dics/index.vue'
  import ProUploadFile from '@/components/core/proUploadFile/index.vue'
  import {
    recordUserIssuePageDataUsingPost,
    recordUserIssueSuccessIssueUsingPost,
    recordUserIssueExecuteIssueUsingPost,
    recordUserIssueGetDataUsingPost,
    RecordUserIssueBoRecordUserIssueSuccessIssue,
    RecordUserIssueBoRecordUserIssueExecuteIssue,
    geoAreaPageDataUsingPost
  } from '@/api'
  // 类型定义
  interface SearchForm {
    recordType: number | null
    recordUrgentType: number | null
    recordStatus: number | null
    recordSolveStatus: number | null
    areaId: number | null
    recordScoreStatus: number | null
    userId: number | null
  }

  // 响应式数据
  const searchForm = ref<SearchForm>({
    recordType: null,
    recordUrgentType: null,
    recordStatus: null,
    recordSolveStatus: null,
    areaId: null,
    recordScoreStatus: null,
    userId: null
  })
  // 小区列表
  const areaList = ref<any>([])
  // 搜索表单配置
  const formItems = computed(() => {
    // 确保能获取到最新的 searchForm 值
    const currentForm = searchForm.value

    return [
      {
        key: 'areaId',
        label: '小区名称',
        type: 'select',
        props: {
          placeholder: '请选择小区',
          options: areaList.value.map((item: any) => ({
            label: item.areaName,
            value: item.id
          }))
        }
      },
      {
        key: 'recordType',
        label: '报事类型',
        type: () =>
          h(DictSelect, {
            dictType: '10200',
            placeholder: '请选择报事类型',
            clearable: true,
            modelValue: currentForm.recordType,
            'onUpdate:modelValue': (value: any) => {
              searchForm.value.recordType = value
            },
            // 添加 onClear 事件处理，点击清空按钮时置空表单值
            onClear: () => {
              searchForm.value.recordType = null
            }
          })
      },
      {
        key: 'recordUrgentType',
        label: '紧急程度',
        type: () =>
          h(DictSelect, {
            dictType: '10310',
            placeholder: '请选择紧急程度',
            clearable: true,
            modelValue: currentForm.recordUrgentType,
            'onUpdate:modelValue': (value: any) => {
              searchForm.value.recordUrgentType = value
            },
            // 添加 onClear 事件处理，点击清空按钮时置空表单值
            onClear: () => {
              searchForm.value.recordUrgentType = null
            }
          })
      },
      {
        key: 'recordStatus',
        label: '处理状态',
        type: () =>
          h(DictSelect, {
            dictType: '10300',
            placeholder: '请选择处理状态',
            clearable: true,
            modelValue: currentForm.recordStatus,
            'onUpdate:modelValue': (value: any) => {
              searchForm.value.recordStatus = value
            },
            // 添加 onClear 事件处理，点击清空按钮时置空表单值
            onClear: () => {
              searchForm.value.recordStatus = null
            }
          })
      },
      {
        key: 'recordSolveStatus',
        label: '解决状态',
        type: () =>
          h(DictSelect, {
            dictType: '10210',
            placeholder: '请选择解决状态',
            clearable: true,
            modelValue: currentForm.recordSolveStatus,
            'onUpdate:modelValue': (value: any) => {
              searchForm.value.recordSolveStatus = value
            },
            // 添加 onClear 事件处理，点击清空按钮时置空表单值
            onClear: () => {
              searchForm.value.recordSolveStatus = null
            }
          })
      },
      {
        key: 'recordScoreStatus',
        label: '评价',
        type: () =>
          h(DictSelect, {
            dictType: '10200',
            placeholder: '请选择评价状态',
            clearable: true,
            modelValue: currentForm.recordScoreStatus,
            'onUpdate:modelValue': (value: any) => {
              searchForm.value.recordScoreStatus = value
            },
            // 添加 onClear 事件处理，点击清空按钮时置空表单值
            onClear: () => {
              searchForm.value.recordScoreStatus = null
            }
          })
      }
    ]
  })

  // 使用 useTable 管理表格数据
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: recordUserIssuePageDataUsingPost,
      apiParams: {
        body: {
          current: 1,
          size: 10
          // recordType: searchForm.value.recordType,
          // recordUrgentType: searchForm.value.recordUrgentType,
          // recordStatus: searchForm.value.recordStatus,
          // recordSolveStatus: searchForm.value.recordSolveStatus,
          // areaId: searchForm.value.areaId
        }
      },
      paginationWrapper: 'body', // 将分页参数包装到 body 对象中
      columnsFactory: () => [
        {
          prop: 'newUser.newName',
          label: '用户名称',
          width: 120
        },
        {
          prop: 'geoArea.areaName',
          label: '小区名称',
          width: 120
        },
        {
          prop: 'dataStatus',
          label: '状态',
          width: 80,
          useSlot: true
        },
        {
          prop: 'recordLongitude',
          label: '经度',
          width: 180
        },
        {
          prop: 'recordLatitude',
          label: '纬度',
          width: 180
        },
        {
          prop: 'recordAddress',
          label: '位置信息',
          width: 120
        },
        {
          prop: 'recordTime',
          label: '报事时间',
          width: 180,
          useSlot: true
        },
        {
          prop: 'recordType',
          label: '报事类型',
          width: 120,
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        },
        {
          prop: 'recordUrgentType',
          label: '紧急程度',
          width: 120,
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        },
        {
          prop: 'recordDescribe',
          label: '问题描述',
          minWidth: 200
        },
        {
          prop: 'recordFile',
          label: '附件',
          minWidth: 200,
          useSlot: true
        },
        {
          prop: 'recordStatus',
          label: '报事处理状态',
          width: 120,
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        },
        {
          prop: 'recordSolveStatus',
          label: '解决状态',
          width: 120,
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        },
        {
          prop: 'recordReplyInfo',
          label: '回复内容',
          minWidth: 200
        },
        {
          prop: 'recordReplyFile',
          label: '回复附件',
          minWidth: 200,
          useSlot: true
        },
        {
          prop: 'recordScoreStatus',
          label: '评价',
          minWidth: 200,
          useSlot: true
        },
        {
          prop: 'recordScoreInfo',
          label: '评价内容',
          minWidth: 200
        },
        {
          prop: 'createTime',
          label: '创建时间',
          width: 200,
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 200,
          fixed: 'right',
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        }
      ]
    }
  })

  const showSearchBar = ref(false)

  // 处理弹框相关
  const processDialogVisible = ref(false)
  const processLoading = ref(false)
  const processFormRef = ref()

  // 解决弹框相关
  const solveDialogVisible = ref(false)
  const solveLoading = ref(false)
  const solveFormRef = ref()

  // 处理表单数据
  const processForm = ref<RecordUserIssueBoRecordUserIssueExecuteIssue>({
    id: undefined,
    recordStatus: undefined,
    recordReplyInfo: '',
    recordReplyFile: ''
  })

  // 文件列表数据
  const replyFileList = ref<any[]>([])

  // 解决表单数据
  const solveForm = ref<RecordUserIssueBoRecordUserIssueSuccessIssue>({
    id: undefined,
    recordReplyInfo: '',
    recordReplyFile: ''
  })

  // 解决文件列表数据
  const solveReplyFileList = ref<any[]>([])

  // 查看详情相关
  const viewDialogVisible = ref(false)
  const viewDetailData = ref<any>(null)

  // 处理表单验证规则
  const processFormRules = {
    recordStatus: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
    recordReplyInfo: [
      { required: true, message: '请输入回复内容', trigger: 'blur' },
      { max: 500, message: '回复内容不能超过500个字符', trigger: 'blur' }
    ]
  }

  // 解决表单验证规则
  const solveFormRules = {
    recordReplyInfo: [
      { required: true, message: '请输入解决回复内容', trigger: 'blur' },
      { max: 500, message: '回复内容不能超过500个字符', trigger: 'blur' }
    ]
  }

  // 页面加载时自动获取数据
  onMounted(() => {
    getData()
    getAreaList()
  })

  const handleSearch = () => {
    searchParams.body.recordType = searchForm.value.recordType || undefined
    searchParams.body.recordUrgentType = searchForm.value.recordUrgentType || undefined
    searchParams.body.recordStatus = searchForm.value.recordStatus || undefined
    searchParams.body.recordSolveStatus = searchForm.value.recordSolveStatus || undefined
    searchParams.body.areaId = searchForm.value.areaId || undefined
    searchParams.body.recordScoreStatus = searchForm.value.recordScoreStatus || undefined
    searchParams.body.userId = searchForm.value.userId || undefined
    getData()
  }
  const resetSearchParams = () => {
    // 重置搜索参数
    searchParams.body.recordType = undefined
    searchParams.body.recordUrgentType = undefined
    searchParams.body.recordStatus = undefined
    searchParams.body.recordSolveStatus = undefined
    searchParams.body.areaId = undefined
    searchParams.body.recordScoreStatus = undefined
    searchParams.body.userId = undefined

    // 重置表单数据 - 逐个设置确保响应式更新
    searchForm.value.recordType = null
    searchForm.value.recordUrgentType = null
    searchForm.value.recordStatus = null
    searchForm.value.recordSolveStatus = null
    searchForm.value.areaId = null
    searchForm.value.recordScoreStatus = null
    searchForm.value.userId = null

    // 重新获取数据
    getData()
  }

  const handleRefresh = () => {
    refreshData()
  }

  // 格式化日期时间
  const formatDateTime = (dateTime?: string) => {
    return dateTime ? dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss') : ''
  }

  // 报事类型文本（作为DictTag的fallback）
  const getRecordTypeText = (type?: number) => {
    const typeMap: Record<number, string> = {
      10200: '类型1',
      1002: '类型2',
      1003: '类型3'
    }
    return typeMap[type || 0] || '未知'
  }

  // 紧急程度文本
  const getUrgentTypeText = (type?: number) => {
    const typeMap: Record<number, string> = {
      10311: '低',
      10312: '中',
      10313: '高'
    }
    return typeMap[type || 0] || '未知'
  }

  // 紧急程度标签样式
  // const getUrgentTypeTagType = (type?: number) => {
  //   const typeMap: Record<number, string> = {
  //     10311: 'success',
  //     10312: 'warning',
  //     10313: 'danger'
  //   }
  //   return typeMap[type || 0] || 'default'
  // }

  // 处理状态文本
  const getRecordStatusText = (status?: number) => {
    const statusMap: Record<number, string> = {
      10300: '待处理',
      10301: '处理中',
      10302: '已完成',
      10303: '已取消'
    }
    return statusMap[status || 0] || '未知'
  }

  // 处理状态标签样式
  // const getRecordStatusTagType = (status?: number) => {
  //   const statusMap: Record<number, string> = {
  //     10300: 'info',
  //     10301: 'warning',
  //     10302: 'success',
  //     10303: 'danger'
  //   }
  //   return statusMap[status || 0] || 'default'
  // }

  // 解决状态文本
  const getSolveStatusText = (status?: number) => {
    const statusMap: Record<number, string> = {
      10210: '待解决',
      10211: '已解决'
    }
    return statusMap[status || 0] || '未知'
  }

  // 解决状态标签样式
  // const getSolveStatusTagType = (status?: number) => {
  //   const statusMap: Record<number, string> = {
  //     10210: 'warning',
  //     10211: 'success'
  //   }
  //   return statusMap[status || 0] || 'default'
  // }

  // 解析附件字符串为数组
  const getAttachmentList = (recordFile: string): Array<{ url: string; [key: string]: any }> => {
    if (!recordFile) return []

    try {
      // 尝试解析JSON字符串
      const parsed = JSON.parse(recordFile)
      if (Array.isArray(parsed)) {
        return parsed.filter((item) => item && item.url)
      }
      return []
    } catch (error) {
      console.error(error)
      // 如果不是有效的JSON，尝试按逗号分割
      if (typeof recordFile === 'string' && recordFile.includes(',')) {
        return recordFile
          .split(',')
          .map((url) => ({ url: url.trim() }))
          .filter((item) => item.url)
      }
      // 单个URL的情况
      if (recordFile.trim()) {
        return [{ url: recordFile.trim() }]
      }
      return []
    }
  }

  // 获取所有图片URL用于预览
  const getImageUrls = (recordFile: string): string[] => {
    const attachments = getAttachmentList(recordFile)
    return attachments
      .filter((attachment) => isImageFile(attachment.url))
      .map((attachment) => attachment.url)
  }

  // 获取图片在预览列表中的索引
  const getImageIndex = (recordFile: string, currentUrl: string): number => {
    const imageUrls = getImageUrls(recordFile)
    return imageUrls.findIndex((url) => url === currentUrl)
  }

  // 判断是否为图片文件
  const isImageFile = (url: string): boolean => {
    if (!url) return false
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg']
    const lowerUrl = url.toLowerCase()
    return imageExtensions.some((ext) => lowerUrl.includes(ext))
  }

  // 查看报事详情
  const handleView = async (row: any) => {
    try {
      // 重置详情数据
      viewDetailData.value = null

      // 打开弹框
      viewDialogVisible.value = true

      // 调用接口获取详情
      const res = await recordUserIssueGetDataUsingPost({
        body: { id: row.id }
      })

      if (res && res.data) {
        viewDetailData.value = res.data
      } else {
        ElMessage.error('获取详情失败')
        viewDialogVisible.value = false
      }
    } catch (error) {
      console.error('获取报事详情失败:', error)
      ElMessage.error('获取详情失败')
      viewDialogVisible.value = false
    }
  }

  // 处理报事
  const handleProcess = (row: any) => {
    // 重置表单
    processForm.value = {
      id: row.id,
      recordStatus: undefined,
      recordReplyInfo: '',
      recordReplyFile: ''
    }

    // 重置文件列表
    replyFileList.value = []

    // 打开处理弹框
    processDialogVisible.value = true
  }

  // 文件上传成功处理
  const handleFileUploadSuccess = (response: any, uploadFile: any) => {
    // 检查response中的数据结构
    if (response && response.data) {
      // 尝试从不同的字段中获取文件URL
      const fileUrl =
        response.data.fileUrl || response.data.url || response.data.path || response.data

      // 查找并更新文件列表中对应的文件
      const fileIndex = replyFileList.value.findIndex((file) => file.uid === uploadFile.uid)
      if (fileIndex !== -1) {
        // 确保文件URL被正确设置
        if (fileUrl && typeof fileUrl === 'string') {
          replyFileList.value[fileIndex].url = fileUrl
        }
      } else {
        console.warn('未找到对应的文件对象，uid:', uploadFile.uid)
      }
    }
  }

  // 解决文件上传成功处理
  const handleSolveFileUploadSuccess = (response: any, uploadFile: any) => {
    // 检查response中的数据结构
    if (response && response.data) {
      // 尝试从不同的字段中获取文件URL
      const fileUrl =
        response.data.fileUrl || response.data.url || response.data.path || response.data

      // 查找并更新文件列表中对应的文件
      const fileIndex = solveReplyFileList.value.findIndex((file) => file.uid === uploadFile.uid)
      if (fileIndex !== -1) {
        // 确保文件URL被正确设置
        if (fileUrl && typeof fileUrl === 'string') {
          solveReplyFileList.value[fileIndex].url = fileUrl
        }
      } else {
        console.warn('未找到对应的文件对象，uid:', uploadFile.uid)
      }
    }
  }

  // 将文件列表转换为字符串
  const convertFileListToString = (fileList: any[]): string => {
    if (!fileList || fileList.length === 0) {
      return ''
    }

    const urls = fileList
      .filter((file) => {
        const hasValidUrl = !!file.url
        const isUploadSuccess = file.loadingState === 0

        // 只取上传成功且有URL的文件
        return hasValidUrl && isUploadSuccess
      })
      .map((file) => file.url)

    // 如果没有有效的URL，返回空字符串而不是空数组的JSON
    if (urls.length === 0) {
      return ''
    }

    const result = JSON.stringify(urls)

    return result
  }

  // 将字符串转换为文件列表
  // const convertStringToFileList = (fileString: string): any[] => {
  //   if (!fileString) return []

  //   try {
  //     const urls = JSON.parse(fileString)
  //     if (Array.isArray(urls)) {
  //       return urls.map((url, index) => ({
  //         name: `文件${index + 1}`,
  //         url: url,
  //         percentage: 100,
  //         loadingState: 0,
  //         uid: Date.now() + index
  //       }))
  //     }
  //   } catch (error) {
  //     console.error('解析文件字符串失败:', error)
  //   }

  //   return []
  // }

  // 处理表单提交
  const handleProcessSubmit = async () => {
    try {
      // 验证表单
      await processFormRef.value?.validate()

      processLoading.value = true

      // 将文件列表转换为字符串
      const fileString = convertFileListToString(replyFileList.value)

      // 准备提交数据
      const submitData = {
        ...processForm.value,
        recordReplyFile: fileString
      }

      // 调用处理接口
      const res = await recordUserIssueExecuteIssueUsingPost({
        body: submitData
      })
      if (res) {
        ElMessage.success('处理成功')
        processDialogVisible.value = false
        // 刷新数据
        getData()
      } else {
        ElMessage.error(res.msg || '处理失败')
      }
    } catch (error) {
      console.error('处理报事失败:', error)
      ElMessage.error('处理失败')
    } finally {
      processLoading.value = false
    }
  }

  // 解决表单提交
  const handleSolveSubmit = async () => {
    try {
      // 验证表单
      await solveFormRef.value?.validate()

      solveLoading.value = true

      // 将文件列表转换为字符串
      const fileString = convertFileListToString(solveReplyFileList.value)

      // 准备提交数据
      const submitData = {
        ...solveForm.value,
        recordReplyFile: fileString
      }
      // 调用解决接口
      const res = await recordUserIssueSuccessIssueUsingPost({
        body: submitData
      })
      if (res) {
        ElMessage.success('解决成功')
        solveDialogVisible.value = false
        // 刷新数据
        getData()
      } else {
        ElMessage.error(res.msg || '解决失败')
      }
    } catch (error) {
      console.error('解决报事失败:', error)
      ElMessage.error('解决失败')
    } finally {
      solveLoading.value = false
    }
  }

  // 解决报事
  const handleSolve = (row: any) => {
    // 重置表单
    solveForm.value = {
      id: row.id,
      recordReplyInfo: '',
      recordReplyFile: ''
    }

    // 重置文件列表
    solveReplyFileList.value = []

    // 打开解决弹框
    solveDialogVisible.value = true
  }

  // 获取小区列表
  const getAreaList = async () => {
    try {
      const params = {
        current: 1,
        size: 100 // 获取足够多的小区
      }
      const res = await geoAreaPageDataUsingPost({ body: params })
      if (res.list) {
        areaList.value = res.list
      }
    } catch (error) {
      console.error('获取小区列表失败:', error)
      ElMessage.error('获取小区列表失败')
    }
  }
</script>

<style lang="scss" scoped>
  .attachment-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
    max-width: 200px;
  }

  .attachment-item {
    display: flex;
    align-items: center;
  }

  .image-preview {
    .attachment-image {
      width: 50px;
      height: 50px;
      cursor: pointer;
      object-fit: cover;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;
        transform: scale(1.05);
      }
    }
  }

  .file-link {
    display: flex;
    gap: 4px;
    align-items: center;
    margin: 2px 0;

    .el-link {
      font-size: 11px;
      white-space: nowrap;
    }
  }

  .text-gray-400 {
    font-size: 12px;
    color: #9ca3af;
  }

  .detail-container {
    .detail-item {
      margin-bottom: 16px;

      label {
        display: inline-block;
        min-width: 80px;
        margin-right: 8px;
        font-weight: 600;
        color: #606266;
      }

      span {
        color: #303133;
      }

      .detail-content {
        padding: 8px 12px;
        margin-top: 4px;
        line-height: 1.5;
        color: #303133;
        word-break: break-word;
        white-space: pre-wrap;
        background-color: #f5f7fa;
        border-radius: 4px;
      }
    }
  }

  .loading-container {
    padding: 20px;
  }
</style>
